<!--
 * @Author: 小花
 * @Date: 2022-05-18 20:47:03
 * @LastEditors: 小花
 * @LastEditTime: 2022-05-18 22:54:23
 * @FilePath: /adminClient/src/components/UpdatePass.vue
 * @Description:
-->
<template>
  <div class="row-box">
    <el-form ref="ruleFormRef" :model="pass" :rules="rules" label-width="120px" class="demo-ruleForm">
      <el-form-item label="原密码:" prop="oldPass">
        <el-input type="password" show-password v-model="pass.oldPass" placeholder="原密码" clearable />
      </el-form-item>
      <el-form-item label="新密码:" prop="newPass1">
        <el-input type="password" show-password v-model="pass.newPass1" placeholder="新密码" clearable />
      </el-form-item>
      <el-form-item label="确认新密码:" prop="newPass2">
        <el-input type="password" show-password v-model="pass.newPass2" placeholder="确认新密码" clearable />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" plain @click="submitForm(ruleFormRef)">保存</el-button>
      </el-form-item>
    </el-form>

  </div>

</template>

<script lang='ts'>
import { defineComponent, reactive, toRefs } from 'vue'
import UpdatePassData, { rules } from '@/model/main/layout/dynamicNav/UpdatePass'
import _cloneDeep from 'lodash/cloneDeep'
import { ElMessage, FormInstance } from 'element-plus'
import { updatePass } from '@/plugins/request/http'
import { Md5 } from 'ts-md5/dist/md5'
import { responseEnum, responseUtil } from '@/plugins/request/responseUtil'
import { pubKeyEncrypt } from '@/plugins/encrypt/rsa'
import { useStore } from '@/plugins/store/store'

export default defineComponent({
  name: 'UpdatePass',
  setup (props, context) {
    const store = useStore()
    const coreData = reactive(new UpdatePassData())

    const submitForm = async (formEl: FormInstance | undefined) => {
      if (!formEl) return
      await formEl.validate((valid, fields) => {
        if (valid) {
          updatePassFn()
        }
      })
    }

    const updatePassFn = async () => {
      const data = _cloneDeep(coreData.pass)
      if (data.newPass1 !== data.newPass2) {
        ElMessage.warning('二次新密码不一致')
        return
      }

      data.oldPass = Md5.hashStr(data.oldPass)
      data.newPass1 = Md5.hashStr(data.newPass1)
      delete data.newPass2
      const encryptData = pubKeyEncrypt(store.publicKey, JSON.stringify(data))
      if (!encryptData) {
        ElMessage.warning('保存失败，请刷新页面后重试')
        return
      }
      const result = await (await updatePass(encryptData)).data as responseUtil
      context.emit('closeDrawer')
      ElMessage({
        type: result.code === responseEnum.OK ? 'success' : 'error',
        message: result.msg
      })
    }

    return {
      ...toRefs(coreData),
      submitForm,
      rules
    }
  }
})
</script>

<style lang='scss' scoped>
.row-box {
  display: flex;
  justify-content: center;
  align-items: center;

  .demo-ruleForm {
    width: 40%;

    .el-button {
      width: 100%;
    }
  }
}
</style>
